#include "filesender.h"

FileSender::FileSender(QObject *parent)
    : QTcpSocket(parent)
{
}

void FileSender::onConnected()
{
    QFile file(fileName);

    if(!file.open(QIODevice::ReadOnly)) {
        emit failed();
        return;
    }

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    QFileInfo fileInfo(file);

    out << quint64(0) << fileInfo.fileName() << file.readAll();
    out.device()->seek(0);
    out << quint64(block.size() - sizeof(quint64));
    QTcpSocket::write(block);
    file.close();

    emit fileSent();
    QTcpSocket::disconnectFromHost();
}

void FileSender::sendFile(const QString &fileName, const QString &hostName, quint16 port)
{
    /*
    ** Checking if another file is being sent.
    */
    if(QTcpSocket::state() != QAbstractSocket::UnconnectedState) {
        emit failed();
        return;
    }

    connect(this, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(failed()));
    this->fileName = fileName;
    QTcpSocket::connectToHost(hostName, port);
}
